//
//  MainViewController.m
//  Megatlon
//
//  Created by Leandro Milmanda on 4/7/12.
//  Copyright 2012 www.lemil.com.ar. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>

#import "DisplayMap.h"
#import "MainViewController.h"
#import "SucursalesDao.h"
#import "CustomPin.h"


@implementation MainViewController

@synthesize mapView,region;



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidLoad];
	
    [[self view] sizeToFit];
    
    
    //Cargar el contenido desde la URL sync
    sucursalService = [SucursalesDao instance];
    
    if(![sucursalService isLoaded])
    {
        [sucursalService load];
    }
    
    [self prepareMap];

}


-(void)prepareMap 
{
    
    [mapView setMapType:MKMapTypeStandard];
	[mapView setZoomEnabled:YES];
	[mapView setScrollEnabled:YES];
    

    NSArray *sucursales = sucursalService.getAll;
    int cantSucursales = sucursalService.getTotalSucursales;
    
    
    
    NSDate *date = [NSDate date] ;
    NSCalendar *calendar = [NSCalendar currentCalendar ];
    NSInteger units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit ;
    NSDateComponents *components = [calendar components:units fromDate:date];
    int weekday = [components weekday] - 1;
    if(weekday == 0) {
        weekday = 7;
    }
    int hour = [components hour];
    int minutes = [components minute];
    
    
    int i;
    for(i = 0; i < cantSucursales; i++){
        
        NSDictionary *unaSucursal = [sucursales objectAtIndex:i];
        
        NSString* nombre = [unaSucursal objectForKey:@"nombre"]; 
        NSString* direccion = [unaSucursal objectForKey:@"direccion"] ;
        
        int estado = [[unaSucursal objectForKey:@"estado"] intValue] ;
        int nro = [[unaSucursal objectForKey:@"id"] intValue] ;
        
        NSString* latitude = [unaSucursal objectForKey:@"latitud"];
        NSString* longitude = [unaSucursal objectForKey:@"longitud"] ;
        
        BOOL isOpened = [sucursalService isOpenedSucursalId:nro atDayNumber:weekday andTime:hour andMinutes:minutes];

        CLLocationCoordinate2D point2d;
         
        point2d.latitude = [latitude floatValue];
        point2d.longitude = [longitude floatValue]; 
        
        //NSLog(@"-Sucursal:%d , estado:%d, opened:%d",nro,estado,isOpened);
        
        DisplayMap *ann = [[[DisplayMap alloc] init] autorelease]; 
        [ann setNro:nro];
        [ann setTitle:nombre];
        [ann setSubtitle:direccion];
        [ann setCoordinate:point2d];
        [ann setEstado:estado];
        [ann setOpened:isOpened];
        
        [mapView addAnnotation:ann];
    }
    
    //float deltax = fabs( maxw - maxe );
    //float deltay = fabs( maxs - maxn );
    //float centerx = maxw + (deltax/2);
    //float centery = maxs + (deltay/2);
    
    //NSLog([NSString stringWithFormat:@"delta-x: %f, delta-y %f",deltax,deltay]);
    //NSLog([NSString stringWithFormat:@"center-x: %f, center-y %f",centerx,centery]);
    
    region.center.latitude =-34.560073f;
    region.center.longitude = -58.456923f;
    region.span.latitudeDelta = 0.15f; //deltax;
    region.span.longitudeDelta = 0.15f;  //deltay;
    
    [mapView setRegion:region animated:YES]; 
    [mapView setDelegate:self];
    
    //[ann release];
    
}


-(void) updateMyMap {
    [mapView setRegion:region animated:YES];    
}

-(MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:(id <MKAnnotation>)annotation 
{    
	MKPinAnnotationView *pinView = nil; 
	if(annotation != mapView.userLocation) {
	
        static NSString *defaultPinID = @"customid";
        
		pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
		if ( pinView == nil ) {
            pinView = [[[CustomPin alloc] initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];
        }
        
		//pinView.pinColor = MKPinAnnotationColorRed; 
		pinView.canShowCallout = YES;
    
        
        UITapGestureRecognizer *tapGesture = 
        [[UITapGestureRecognizer alloc] initWithTarget:self
                                                action:@selector(calloutTapped:)];
        [pinView addGestureRecognizer:tapGesture];
        [tapGesture release];
        
        int e =  [((DisplayMap *)annotation) estado]   ;
        BOOL o = [((DisplayMap *)annotation) opened] ;
        //NSLog(@"-Sucursal:%d , estado:%d, opened:%d",s,e,o);
        
        switch (e) {
            case 1:
            case 2:
                if(o){
                    pinView.image = [UIImage imageNamed:@"mapa_punto_on.png"];
                } else {
                    pinView.image = [UIImage imageNamed:@"mapa_punto.png"];
                }
                break;
            default:
                pinView.image = [UIImage imageNamed:@"mapa_punto_out.png"];
                break;
        } 
        
        //pinView.image = [UIImage imageNamed:@"mapa_punto.png"];
        

    } 
    
	return pinView;
}

-(void) calloutTapped:(UITapGestureRecognizer *)recognizer { 
    
    MKPinAnnotationView *pinView = ((MKPinAnnotationView*)recognizer.view);
    DisplayMap *dMap = [pinView annotation];
    
    [self showInfoWithSelected:[dMap nro]];

    [dMap release];
    [pinView release];
}

- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller
{
    [self dismissModalViewControllerAnimated:YES];
}

- (IBAction)showInfo:(id)sender
{    
    [self showInfoWithSelected:0];
}

-(IBAction) showInfoWithSelected:(int)sucid {

    FlipsideViewController *flipedSideViewController = [[[FlipsideViewController alloc] initWithNibName:@"FlipsideView" bundle:nil] autorelease]; 
    flipedSideViewController.delegate = self;
    flipedSideViewController.selectedSucursal = sucid;
    
    flipedSideViewController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentModalViewController:flipedSideViewController animated:YES];

}



- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
	[mapView release];
    [super dealloc];
}

@end
